import collections

from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import render

from web import models


def statistics(request, project_id):
    """统计页面"""

    return render(request, 'statistics.html')


def statistics_priority(request, project_id):
    """优先级饼图接口"""

    start = request.GET.get('start')
    end = request.GET.get('end')

    # 1. 构造字典
    data_dict = collections.OrderedDict()
    for k, v in models.Issues.priority_choices:
        data_dict[k] = {'name': v, 'y': 0}

    # 2. 找到所有问题 按优先级分组
    res = models.Issues.objects.filter(project_id=project_id,
                                       create_datetime__gte=start,
                                       create_datetime__lt=end).values('priority').annotate(ct=Count('id'))

    # 3. 构造返回数据
    for item in res:
        data_dict[item['priority']]['y'] = item['ct']

    return JsonResponse({'status': True, 'data': list(data_dict.values())})


def statistics_project_user(request, project_id):
    """文件进度柱状图"""

    start = request.GET.get('start')
    end = request.GET.get('end')

    # 1. 根据所有问题，指派用户进行分组
    all_user_dict = collections.OrderedDict()
    all_user_dict[request.tracer.project.creator.id] = {
        'name': request.tracer.project.creator.name,
        'status': {item[0]: 0 for item in models.Issues.status_choices}
    }
    all_user_dict[None] = {
        'name': '未指派',
        'status': {item[0]: 0 for item in models.Issues.status_choices}
    }

    # 2. 项目成员
    user_list = models.Participant.objects.filter(project_id=project_id)
    for item in user_list:
        all_user_dict[item.user_id] = {
            'name': item.user.name,
            'status': {item[0]: 0 for item in models.Issues.status_choices}
        }

    # 3. 获取所有相关问题
    res = models.Issues.objects.filter(project_id=project_id, create_datetime__gte=start, create_datetime__lt=end)
    for item in res:
        if not item.assign:
            all_user_dict[None]['status'][item.status] += 1
        else:
            all_user_dict[item.assign_id]['status'][item.status] += 1

    # 4. 获取所有的成员
    categories = [data['name'] for data in all_user_dict.values()]

    # 5. 每个人，有多少跟数据
    data_result_dict = collections.OrderedDict()
    for item in models.Issues.status_choices:
        data_result_dict[item[0]] = {'name': item[1], 'data': []}

    for k, v in models.Issues.status_choices:
        for row in all_user_dict.values():
            count = row['status'][k]
            data_result_dict[k]['data'].append(count)

    context = {
        'status': True,
        'data': {
            'categories': categories,
            'series': list(data_result_dict.values())
        }
    }
    print(context)

    return JsonResponse(context)
